# Create your views here.

from django.shortcuts import render_to_response
from petra.rsdownloads.models import *

from django.http import HttpResponse
from django.core import serializers

from django.utils import simplejson

def view_download(request, download_id):
	"""
		Prepare data for view of download
		download_id
	"""	

	#Get the download
	try:
		d = Download.objects.get(id = download_id)
	except:
		#Download not found
		return render_to_response("incorrect_download.html")
	else:
		#Render data with template
		params = dict()
		params["download"] = d
		return render_to_response("view_download.html", params)


def view_download_status(request, download_id):
	"""
		Show download status if any
	"""
	try:
		d = Download.objects.get(id = download_id)
	except:
		return render_to_response("incorrect_download.html")
	else:
		#Try to get a valid DownloadProgress object
		try:
			dp = d.downloadprogress
		except:
			dp = DownloadProgress()
		

		#Check if we have some special encodings in the url
		if request.GET.has_key("enc"):
			#Check encoding
			encoder = "xml"
			mime = "text/xml"
			if request.GET["enc"] == "json":
				#Try some json encoding
				encoder = "json"
				mime = "text/javascript"
			serialized_data = serializers.serialize(encoder, [dp])	
			return HttpResponse(serialized_data, mimetype = mime)
		else:
			#Show again the view_download function (this is a bad solution, time :P)
			return view_download(request, download_id)

def start_download(request, download_id):
	"""
		Start the download progress for download_id selected
	"""
	data = dict()
	try:
		#Try to get a valid download
                d = Download.objects.get(id = download_id)
        except:
                data["result"] = "0" 
        else:
		download = Downloader(d)
		download.start()
		data["result"] = "1"

	return HttpResponse(simplejson.dumps(data), mimetype = "text/javascript")

def alter_download_priority(request, download_id):
	"""
		Alter priority
	"""
	data = dict()
	#Check params
	if request.GET.has_key("priority"):
		priority = int(request.GET["priority"])
		try:
			#Try to get a valid download
        	        d = Download.objects.get(id = download_id)
        	except:
                	data["result"] = "0"
        	else:
			d.alter_priority(priority)	
			data["result"] = "1"
	else:
		data["result"] = "0"

	return HttpResponse(simplejson.dumps(data), mimetype = "text/javascript")

def latests_downloads(request):
	"""
		Get the latests download ordered by the model
		in xml or json format
	"""
	num = 10
	encoder = "xml"
	mime = "text/xml"
	
	#Output is selected with the param "enc" if this param does not
	#exists, default output is xml
	if request.GET.has_key("enc"):
		if request.GET["enc"] == "json":
			encoder = "json"
			mime = "text/javascript"

	if request.GET.has_key("num"):
		try:
			num = int (request.GET["num"])
		except:
			return HttpResponse("", mime)

	#Get the latestsdownloads and convert to selected output format
	data = Download.LatestsDownloads(num)
	serialized_data = serializers.serialize(encoder, data)
        return HttpResponse(serialized_data, mimetype = mime)

def add_download(request):
	"""
		Add a new download (single download).
	"""

	encoder = "xml"
	mime = "text/html"

	#Get params from request
	
	if not request.GET.has_key("link"):
		#Error, the param link is needed
		response = 0
	else:
		#Now get the link and additiona params
		link = request.GET["link"]

		if request.GET.has_key("enc"):
			if request.GET["enc"] == "json":
				encoder = "json"
				mime = "text/javascript"

		if request.GET.has_key("check"):
			check = True
		else:
			check = False

		if request.GET.has_key("name"):
			name = request.GET["name"]
		else:
			name = link.split("/")[-1]

		if check:
			#Check if the link is valid
			pass

		d = Download(name = name, url = link)
		d.save()

		response = 1

	data = dict()
	data["result"] = response

	#Hack, always json
	return HttpResponse(simplejson.dumps(data), mimetype = "text/javascript")



def add_multiple_downloads(request):
        """
                Add a list of downloads to queue.
        """

        encoder = "xml"
        mime = "text/html"

        #Get params from request
        if not request.GET.has_key("links"):
                #Error, the param links is required
                response = 0
        else:
		#Links are indicated in a param called links, and are separated
		#by character ";"
                links = request.GET["links"].split(";")

                if request.GET.has_key("enc"):
                        if request.GET["enc"] == "json":
                                encoder = "json"
                                mime = "text/javascript"

		#Now iterate over all the list and create new downloads, check if the link is empty
		for link in links:
			print "Link: %s" % link
			if link <> "":
				name = link.split("/")[-1]
	                	d = Download(name = name, url = link)
                		d.save()

                response = 1

        data = dict()
        data["result"] = response

        #Hack, always json
        return HttpResponse(simplejson.dumps(data), mimetype = "text/javascript")
